package com.pioneer.fationservice.serviceinfos;

import java.util.HashMap;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.utils.DistanceUtil;
import com.pioneer.fationservice.R;
import com.pioneer.fationservice.commons.SystemData;
import com.pioneer.fationservice.commons.SystemHttpURL;
import com.pioneer.fationservice.helpers.ConfigHelper;
import com.pioneer.fationservice.models.ResponseObject;
import com.pioneer.fationservice.models.VerfyCodeModel;
import com.pioneer.fationservice.parsers.LoginParser;
import com.pioneer.fationservice.parsers.VerfyCodeParser;
import com.pioneer.fationservice.receivers.SmsReceiver;
import com.pioneer.fationservice.receivers.SmsReceiver.OnSmsReceivedListener;
import com.pioneer.fationservice.services.LocationService;

/**
 * 注册页面
 * @author Mrper
 *
 */
public class LoginActivity extends FinalActivity implements TextWatcher {

	@ViewInject(id=R.id.layout_actionbar_txtTitle) private TextView txtTitle;//标题文本栏
	@ViewInject(id=R.id.activity_login_etPhone) private EditText etPhone;//电话
	@ViewInject(id=R.id.activity_login_etValidate) private EditText etValidate;//验证码
	@ViewInject(id=R.id.activity_login_txtGetVerfycode,click="onGetVerfyCodeClick") private TextView txtGetVerfyCode;//验证码获取按钮
	@ViewInject(id=R.id.activity_login_btnValidate,click="onValidateClick") private Button btnValiate;//下一步
	
	private long exitTime = 0;//退出时刻
	private int leftTime = 60;//剩余时间
	private SmsReceiver smsReceiver;//短信接收者
	private boolean isStopTimer = true;//是否停止定时器

	
	private static final int MSG_COUNT_SECOND = 0x001;//计秒信息
	private static final int MSG_RESTART_STOP_SECOND = 0x002;//重启计秒
	
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case MSG_COUNT_SECOND:
				txtGetVerfyCode.setText("剩余"+leftTime+"秒");
				break;
			case MSG_RESTART_STOP_SECOND:
				leftTime = 60;
				isStopTimer = true;
				txtGetVerfyCode.setText("重发验证码");
				txtGetVerfyCode.setEnabled(true);
				break;
			}
		};
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		txtTitle.setText("验证会员");
		etPhone.addTextChangedListener(this);
		etValidate.addTextChangedListener(this);
		initSmsReceiver();//注册短信接收器
	}
	

	/**
	 * 点击返回的操作
	 * @param v
	 */
	public void onBackClick(View v){
		this.finish();
		overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
	}
	
	/**
	 * 获取验证码的点击操作
	 * @param v
	 */
	public void onGetVerfyCodeClick(View v){
		if(!checkInput(etPhone,"^1[3|5|7|8|][0-9]{9}$","手机号格式不正确!")) return;
		requestVerfyCode(etPhone.getText().toString());//请求验证信息
	}
	
	/**
	 * 激活会员的操作
	 * @param v
	 */
	public void onValidateClick(View v){
		if(!checkInput(etPhone,"^1[3|5|7|8|][0-9]{9}$","手机号格式不正确!") 
				|| !checkInput(etValidate,"[A-Za-z0-9]{6}","验证码格式错误!"))
			return;
		isStopTimer = true;//停止定时器
		handler.sendEmptyMessage(MSG_RESTART_STOP_SECOND);//重置计数器
		requestValidateVIP(etPhone.getText().toString(), etValidate.getText().toString());
	}
	
    /**
     * 检测输入参数
     * @param et
     * @param errorMessage
     * @return
     */
    public boolean checkInput(EditText et,String regExp,String errorMessage){
    	if(et.getText().toString().matches(regExp)) return true;
    	et.setError(errorMessage);
    	return false;
    }
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK){
			long nowTime = System.currentTimeMillis();
			if(nowTime - exitTime > 800){
				exitTime = nowTime;
				Toast.makeText(this,"再按一次退出程序",Toast.LENGTH_SHORT).show();
				return true;
			}
			this.finish();
			System.exit(0);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	/**
	 * 开始计秒
	 */
	public void startCountSecond(){
		new Thread(new Runnable(){
			@Override
			public void run() {
				while(true){
					try {
						leftTime--;
						handler.sendEmptyMessage(MSG_COUNT_SECOND);
						if(isStopTimer || leftTime <= 0){//此时应该停止计时，重置按钮、时间
							handler.sendEmptyMessage(MSG_RESTART_STOP_SECOND);
							return;
						}
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
	
	/**
	 * 注册短信接收者
	 */
	public void initSmsReceiver(){
		smsReceiver = new SmsReceiver();
		smsReceiver.setOnSmsReceivedListener(new OnSmsReceivedListener() {
			@Override
			public void onSmsReceived(String message) {
				etValidate.setText(message);
			}
		});
		IntentFilter filter = new IntentFilter(SmsReceiver.TAG);
		filter.addAction("android.provider.Telephony.SMS_RECEIVED");
		filter.setPriority(800);
		this.registerReceiver(smsReceiver, filter);
	}
	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(smsReceiver);
	}
	

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,int after) {
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
	}

	@Override
	public void afterTextChanged(Editable s) {
		btnValiate.setEnabled(etPhone.getText().toString().matches("^1[3|5|7|8|][0-9]{9}$") 
				&& etValidate.getText().toString().matches("[A-Za-z0-9]{6}"));
	}
	
	/**
	 * 请求验证码
	 * @param phoneNumber
	 */
	public void requestVerfyCode(String phoneNumber){
		final ProgressDialog dialog = ProgressDialog.show(this, "", "请稍等...");
    	FinalHttp finalHttp = new FinalHttp();                                        
    	finalHttp.configCharset("UTF-8");
    	finalHttp.configTimeout(10*1000);
    	finalHttp.addHeader("Content-Type", "html/text");
    	finalHttp.addHeader("Conection", "Keep-Alive");
    	finalHttp.addHeader("Cache-Control", "no-cache");
    	HashMap<String,String> params = new HashMap<String,String>();
    	params.put("phone", phoneNumber);
    	params.put("authkey",SystemData.HTTP_KEY);
    	finalHttp.post(SystemHttpURL.URL_SEND_VERFYCODE, new AjaxParams(params),new AjaxCallBack<String>(){
    		@Override
    		public void onFailure(Throwable t, int errorNo, String strMsg) {
    			super.onFailure(t, errorNo, strMsg);
    			if(dialog!=null) dialog.dismiss();
    			System.out.println("验证码发送结果：" + strMsg);
    			Toast.makeText(LoginActivity.this, "网络错误，请重试!"+strMsg, Toast.LENGTH_SHORT).show();
    		}
    		@Override
    		public void onSuccess(String str) {
    			super.onSuccess(str); 
    			if(dialog!=null) dialog.dismiss();
    			System.out.println("验证码发送结果：" + str);
    			//转换数据
    			VerfyCodeModel model =  new VerfyCodeParser(str).getResponseObject();
    			switch(model.status){
    			case 1://成功
    				txtGetVerfyCode.setEnabled(false);//停用验证码控件
    				txtGetVerfyCode.setText("剩余"+leftTime+"秒");
    				etValidate.setText(model.verfyCode);
    				Toast.makeText(LoginActivity.this, "验证码已发送!有效时间为30分钟，60秒内不能重发!", Toast.LENGTH_SHORT).show();
    				Toast.makeText(LoginActivity.this, "验证码：" + model.verfyCode, 60*1000).show();
    				startCountSecond();//开始计秒
    				break;
    			default:
    				Toast.makeText(LoginActivity.this, model.msg, Toast.LENGTH_SHORT).show();
    				break;
    			}
    		}
    	});
	}
	
	/**
	 * 请求激活会员
	 * @param phoneNumber
	 * @param verfycode
	 */
	public void requestValidateVIP(String phoneNumber,String verfycode){
		final ProgressDialog dialog = ProgressDialog.show(this, "", "正在验证会员...");
    	FinalHttp finalHttp = new FinalHttp();
    	finalHttp.configCharset("UTF-8");
    	finalHttp.configTimeout(10*1000);
    	finalHttp.addHeader("Content-Type", "html/text");
    	finalHttp.addHeader("Conection", "Keep-Alive");
    	finalHttp.addHeader("Cache-Control", "no-cache");
    	HashMap<String,String> params = new HashMap<String,String>();
    	params.put("phone", phoneNumber);
    	params.put("varcode", verfycode);
    	params.put("authkey", SystemData.HTTP_KEY);
    	finalHttp.post(SystemHttpURL.URL_VERFY_PHONE, new AjaxParams(params),new AjaxCallBack<String>(){
    		@Override
    		public void onFailure(Throwable t, int errorNo, String strMsg) {
    			super.onFailure(t, errorNo, strMsg);
    			if(dialog!=null) dialog.dismiss();
    			Toast.makeText(LoginActivity.this, "网络错误，请重试!", Toast.LENGTH_SHORT).show();
    		}
    		@Override
    		public void onSuccess(String str) {
    			super.onSuccess(str);
    			if(dialog!=null) dialog.dismiss();
    			ResponseObject model = new LoginParser(str).getResponseObject();
    			if(model!=null){
	    			switch(model.status){
	    			case 1://成功
	    				System.out.println("验证用户信息 -- 返回结果："+str);
	    				ConfigHelper.getInstance(LoginActivity.this).getConfigEditor()
	    					.putInt("uid", SystemData.uid).commit();
	    				Toast.makeText(LoginActivity.this, "验证成功！", Toast.LENGTH_SHORT).show();
	    				//进入到主页
	        			startActivity(new Intent(LoginActivity.this,MainActivity.class));
	        			LoginActivity.this.finish();//关闭验证页面
	        	        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
	    				break;
	    			default:
	    				Toast.makeText(LoginActivity.this, model.msg, Toast.LENGTH_SHORT).show();
	    				break;
	    			}
    			}else{
    				Toast.makeText(LoginActivity.this, "网络错误，请重试！", Toast.LENGTH_SHORT).show();
    			}
    		}
    	});
	}

}
